package com.zirenx.common.config;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Invocation;
import com.jfinal.core.*;
import com.jfinal.kit.ReflectKit;
import com.jfinal.log.Log;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.zirenx.utils.LogUtils;
import com.zirenx.utils.R;

/**
 * ActionHandler 扩展类
 * @author zirenx
 * handle 重写
 */
public class MyActionHandler extends ActionHandler{

	private static final Log log = Log.getLog(MyActionHandler.class);
	
	/**
	 * 重写
	 */
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		if (target.indexOf('.') != -1) {
			return ;
		}
		
		isHandled[0] = true;
		String[] urlPara = {null};
		Action action = actionMapping.getAction(target, urlPara);
		
		if (action == null) {
			if (log.isWarnEnabled()) {
				String qs = request.getQueryString();
				String message = "404 Action Not Found: " + (qs == null ? target : target + "?" + qs);
				log.warn(message);
				LogUtils.warn(this.getClass(),message,request);
			}
			
			//是否异步
			if(isAjax(request)) {
				renderManager.getRenderFactory().getJsonRender(R.error().put("msg", "404")).setContext(request, response).render();	
			}else {
				renderManager.getRenderFactory().getErrorRender(404).setContext(request, response).render();	
			}
			return ;
		}

		super.handle(target, request, response, isHandled);
	}

    /**
     * 是否异步请求
      * @param request
     * @return
     */
	protected boolean isAjax(HttpServletRequest request){
        String header = request.getHeader("X-Requested-With");
        if(header!=null && header.equals("XMLHttpRequest")) {
            return true;
        }
        return false;
    }
}
